package com.example.zn.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.zn.dto.Result;
import com.example.zn.entity.User;

import com.example.zn.service.UserService;
import com.example.zn.mapper.UserMapper;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
* @author ZN
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-03-18 09:39:04
*/
@Service
public  class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {
    @Override
    public Result login(User user){
        QueryWrapper<User> query= Wrappers.query(User.class);
        query.eq("username",user.getUsername());
        User a = getOne(query);
        if (Objects.isNull(a)){
            return  Result.fail().setMsg("用户不存在");
        }
        if(Objects.equals(a.getPassword(),user.getPassword())){
            return Result.ok().setMsg("登录成功").setData(a);
        }
        return Result.fail().setMsg("密码错误").setCode(2);
    }
    @Override
    public Result reg(User user) {
        //执行注册前需要先检查用户名是否重复
        //创建查询条件构造器 (select * from admin  where username=XXX)
        QueryWrapper<User> query = Wrappers.query(User.class);
        query.eq("username",user.getUsername());
        //根据给定的条件构造器查询对象
        User b = getOne(query);
        if(Objects.nonNull(b)){
            return Result.fail().setMsg("该账号已存在");
        }

        //生成随机盐
        String salt = RandomUtil.randomString(6);
        user.setSalt(salt);
        //将随机盐和输入的密码组合加密
        String pwd = user.getPassword() + salt;
        //使用MD5对组合后的密码加密
        pwd = SecureUtil.md5(pwd);
        //填充加密后的密码到对象中
        user.setPassword(pwd);
        //执行添加 并判断
        if(save(user)){
            return Result.ok().setMsg("添加成功").setData(user);
        }
        return Result.fail().setMsg("添加失败").setCode(1);
    }

}




